import Taro from '@tarojs/taro'
import {View, Picker} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import './index.less'
import {connect} from "@tarojs/redux";

@connect(state => ({
  pca: state.pca,
}))
export default class SearchBar extends Taro.Component {

  componentDidMount() {
    this.props.dispatch({
      type: 'pca/getPca',
      payload: {
        send_cities: 0,
      },
    });
  };

  navigateTo = url => {
    Taro.navigateTo({url: url})
  }

  // picker选择数据动态渲染
  onColumnchange = (e) => {
    const {dispatch, pca: {list, pickerRange}} = this.props;
    const newPickerRange = JSON.parse(JSON.stringify(pickerRange));
    const {column, value} = e.detail;

    if (column === 0) {
      newPickerRange[1] = [];
      list[value].children.forEach(item => {
        newPickerRange[1].push({
          key: item.code,
          name: item.name,
          children: item.children,
        })
      });

      newPickerRange[2] = [];
      list[value].children[0].children.forEach(item => {
        newPickerRange[2].push({
          key: item.code,
          name: item.name,
        })
      });
    }

    if (column === 1) {
      newPickerRange[2] = [];
      pickerRange[1][value].children && pickerRange[1][value].children.forEach(item => {
        newPickerRange[2].push({
          key: item.code,
          name: item.name,
        })
      });
    }

    dispatch({
      type: 'pca/save',
      payload: {
        pickerRange: newPickerRange,
      },
    })
  }

  // picker赋值
  onChange = (e) => {
    const {value} = e.detail;
    const {dispatch, pca: {list}} = this.props;
    const detail = list[value[0] || 0].children[value[1] || 0].children[value[2] || 0];
    dispatch({
      type: 'pca/save',
      payload: {
        showValue: {
          county_code: detail.key || '',
          county_name: detail.name || '',
        }
      },
    })
  }

  render() {
    const {pca: {pickerRange, showValue}} = this.props;

    return (
      <View className='search-wrapper'>
        <Picker
          className="location"
          mode="multiSelector"
          range={pickerRange}
          rangeKey="name"
          onColumnchange={this.onColumnchange}
          onChange={this.onChange}
        >
          <View className="text">{showValue.county_name}</View>
        </Picker>
        <View className='search' onClick={this.navigateTo.bind(this, `/pages/project_detail/index`)}>
          <AtIcon value='search' size='14'></AtIcon>
          <Text className='text'>查找您感兴趣的项目</Text>
        </View>
      </View>
    )
  }
}
